package com.example.controller;

import com.example.service.CacheService;
import com.example.service.ICache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;

import java.util.concurrent.TimeUnit;

@Controller
public class RedisTester {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private CacheService cacheService;
    @Autowired
    private ICache cache;

    public void testCache() {
        cacheService.testCache("bbbb");
    }

    public void testCache2() {
        cache.test1("aaaaaaaaaaaaa");
    }

    public String testSetnx() {

        Boolean success = false;
        do {
            success = stringRedisTemplate.opsForValue().setIfAbsent("kk1", "aaaa", 3000, TimeUnit.MILLISECONDS);
            if (success) {
                System.out.println(Thread.currentThread().getName() + " get the lock!!");
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                stringRedisTemplate.delete("kk1");
            } else {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                System.out.println(Thread.currentThread().getName() + " do not get the lock!!");

            }
        } while (!success);

        return null;
    }

}
